package com.edu.buservice.biz.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.edu.buservice.biz.RoleManger;
import com.edu.buservice.biz.TenantManger;
import com.edu.buservice.biz.config.CommonConfig;
import com.edu.buservice.biz.covert.TenantCovert;
import com.edu.buservice.biz.covert.UserInfoCovert;
import com.edu.buservice.biz.model.Request.TenantRequest;
import com.edu.buservice.biz.model.dto.TenantInfoDTO;
import com.edu.buservice.dal.model.SysTenant;
import com.edu.buservice.dal.model.SysUsers;
import com.edu.buservice.dal.service.SysTenantService;
import com.edu.buservice.dal.service.SysUsersService;
import com.edu.buservice.facade.model.response.BaseUserInfoDTO;
import com.edu.buservice.util.TenantIdGeneratorUtil;
import com.edu.buservice.util.model.PageQuery;
import com.edu.buservice.util.model.PageResult;
import com.edu.buservice.util.model.enums.ErrorCodeEnum;
import com.edu.buservice.util.model.error.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-02-09 18:39
 **/

@Component
@Slf4j
public class TenantMangerImpl implements TenantManger {

	@Autowired
	private SysTenantService sysTenantService;

	@Autowired
	private SysUsersService sysUsersService;

	@Autowired
	private RoleManger roleManger;
	@Autowired
	private CommonConfig  commonConfig;

	//根据租户ID获取租户信息
	public TenantInfoDTO getTenantInfoByTenantId(String tenantId) {

		if(StrUtil.isBlank(tenantId)){
			throw new BizException(ErrorCodeEnum.TENANT_ID_CANNOT_BE_NULL);
		}

		SysTenant tenantInfoByTenantId = sysTenantService.getTenantInfoByTenantId(tenantId);

		return TenantCovert.convert(tenantInfoByTenantId);



	}

	@Override
	public List<TenantInfoDTO> batchQueryTenantInfo(List<String> tenantIds) {

		if(CollectionUtil.isEmpty(tenantIds)){
			return Collections.emptyList();
		}

		List<SysTenant> tenantInfoByTenantIds = sysTenantService.batchQueryTenantInfo(tenantIds);

		if(CollectionUtil.isEmpty(tenantInfoByTenantIds)){
			return Collections.emptyList();
		}

		return tenantInfoByTenantIds.stream().map(TenantCovert::convert).toList();
	}

	@Override
	public String addTenant(TenantRequest tenantRequest) {

		if(tenantRequest == null){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR);
		}

		//生成租户ID，6-8位纯英文
		String tenantId = TenantIdGeneratorUtil.generateTenantId();


		//创建租户
		sysTenantService.createTenant(tenantId, tenantRequest.getTenantName());


		//初始化管理员
		List<String> adminId = tenantRequest.getAdminId();

		//验证管理员ID是否为空和身份信息
		if(CollectionUtil.isEmpty(adminId)){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR, "管理员ID不可以为空");
		}

		for (String id : adminId) {
			SysUsers userInfoById = sysUsersService.getUserInfoById(id);

			if(userInfoById == null){
				throw new BizException(ErrorCodeEnum.PARAM_ERROR, "管理员ID不存在");
			}
			//创建该租户新的账号
			userInfoById.setTenantId(tenantId);
			String userId = sysUsersService.addUserInfo(userInfoById);

			String roleId = commonConfig.getMerchantDefaultRole();
			// 添加用户角色关系
			roleManger.addUserRole(userId, roleId);
		}

		return tenantId;
	}

	@Override
	public PageResult<TenantInfoDTO> queryTenantInfo(PageQuery<TenantRequest> pageQuery) {

		if(pageQuery == null){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR);
		}

		TenantRequest query = pageQuery.getQuery();


		SysTenant convert = TenantCovert.convert(query);

		PageQuery<SysTenant> sysTenantPageQuery =new PageQuery<>();
		sysTenantPageQuery.setPageNum(pageQuery.getPageNum());
		sysTenantPageQuery.setPageSize(pageQuery.getPageSize());
		sysTenantPageQuery.setQuery(convert);
		PageResult<SysTenant> sysTenantPageResult = sysTenantService.queryTenant(sysTenantPageQuery);

		if(sysTenantPageResult == null){
			throw new BizException(ErrorCodeEnum.SYSTEM_ERROR);
		}

		PageResult<TenantInfoDTO> res = new PageResult<>();
		res.setTotal(sysTenantPageResult.getTotal());
		res.setCurrentPage(sysTenantPageResult.getCurrentPage());
		res.setTotalPages(sysTenantPageResult.getTotalPages());

		if(sysTenantPageResult.getRecords() == null){
			log.info("TenantMangerImpl queryTenantInfo 租户信息为空,{}", pageQuery);
			return res;
		}

		List<TenantInfoDTO> tenantInfoDTOS = sysTenantPageResult.getRecords().stream().map(TenantCovert::convert).toList();

		//获取该租户下所有的管理员
		tenantInfoDTOS.forEach(tenantInfoDTO -> {
			List<SysUsers> userInfoByTenantId = sysUsersService.getUserInfoByTenantId(tenantInfoDTO.getTenantId());

			if(CollectionUtil.isEmpty(userInfoByTenantId)){
				return;
			}

			List<BaseUserInfoDTO> collect = userInfoByTenantId.stream().map(UserInfoCovert::covertToUserInfo).toList();

			tenantInfoDTO.setUserInfoList(collect);
		});

		res.setRecords(tenantInfoDTOS);


		return res;
	}

	@Override
	public Boolean deleteTenant(String tenantId) {

		if(StrUtil.isBlank(tenantId)){
			throw new BizException(ErrorCodeEnum.TENANT_ID_CANNOT_BE_NULL);
		}

		//删除租户信息
		sysTenantService.removeById(tenantId);

		//删除租户下的所有用户
		sysUsersService.remove(new LambdaQueryWrapper<SysUsers>().eq(SysUsers::getTenantId, tenantId));

		//TODO 发布删除租户事件，释放资源

		return null;
	}

	@Override
	public Boolean editTenant(TenantRequest tenantRequest) {

		if(tenantRequest == null){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR);
		}

		//更新租户信息
		SysTenant convert = TenantCovert.convert(tenantRequest);
		sysTenantService.updateTenant(convert);


		List<String> adminId = tenantRequest.getAdminId();

		if(CollectionUtil.isNotEmpty(adminId)){

			//获取该租户下所有的管理员
			List<SysUsers> userInfoByTenantId = sysUsersService.getUserInfoByTenantId(tenantRequest.getTenantId());

			//如果不为null,筛选出来删除的管理员和新增的管理员
			if(CollectionUtil.isNotEmpty(userInfoByTenantId)){
				List<String> oldUserIdList = userInfoByTenantId.stream().map(SysUsers::getUserId).toList();

				//新增的管理员
				List<String> newUserIdList = adminId.stream().filter(id -> !oldUserIdList.contains(id)).toList();

				if (CollectionUtil.isNotEmpty(newUserIdList)){
					//新增管理员
					newUserIdList.forEach(id -> {
						SysUsers userInfoById = sysUsersService.getUserInfoById(id);
						if(userInfoById == null){
							throw new BizException(ErrorCodeEnum.PARAM_ERROR, "管理员ID不存在");
						}
						userInfoById.setTenantId(tenantRequest.getTenantId());
						sysUsersService.addUserInfo(userInfoById);
					});
				}

				//删除的管理员
				List<String> delUserIdList = oldUserIdList.stream().filter(id -> !adminId.contains(id)).toList();

				if (CollectionUtil.isNotEmpty(delUserIdList)){
					sysUsersService.removeByUserId(delUserIdList);

					//删除用户下线
					for (String id : delUserIdList){
						StpUtil.logout(id);
					}
				}

			}
		}


		return Boolean.TRUE;
	}

	@Override
	public Boolean updateStatus(TenantRequest tenantRequest) {

		if(tenantRequest == null){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR);
		}

		if(tenantRequest.getStatus() == null){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR, "状态不能为空");
		}

		if(StrUtil.isBlank(tenantRequest.getTenantId())){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR, "租户ID不能为空");
		}

		Integer status = tenantRequest.getStatus();

		if(status != 0 && status != 1){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR, "状态码错误");
		}

		SysTenant convert = TenantCovert.convert(tenantRequest);
		sysTenantService.updateTenant(convert);
		return Boolean.TRUE;

	}

	@Override
	public Boolean updateTenantToken(String tenantId, Long token) {
		if(StrUtil.isBlank(tenantId)){
			throw new BizException(ErrorCodeEnum.PARAM_ERROR, "租户ID不能为空");
		}
		return sysTenantService.updateTenantToken(tenantId, token);

	}

}
